package m.jclecai.com.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.ShowInvitedFriendActivity;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.HttpManager;

/**
 * Created by ZD on 2017/6/28.
 */

public class InvitedFriendFragment extends BaseFragment {


    UserBean userBean;

    @BindView(R.id.ll_friend_list)
    LinearLayout mLlFriendList;

    //这里是推广的内容；
    @BindView(R.id.ll_tui_guang)
    LinearLayout mLlTuiGuang;

    //这里是推广的内容；
    @BindView(R.id.ll_container)
    LinearLayout mLlContainer;




    @Override
    public int getLayoutId() {
        return R.layout.fragment_invited;
    }

    @Override
    public void initData() {
        super.initData();

        checkLogin(new Callback(){

            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                init();
            }

            @Override
            public void callbackField() {
                super.callbackField();
                getActivity().finish();
            }
        });
    }

    public void init(){
        userBean = PreferenceUtil.readUser(getContext());


        //请求数据的操作；
        getData();

    }


    @OnClick(R.id.tv_friend_list)
    void clickFriendList() {
        startActivity(new Intent(getActivity(), ShowInvitedFriendActivity.class));
    }


    public void getData() {

        showDialog();
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user",PreferenceUtil.getUserName(getActivity()));
        paramsMap.put("password",PreferenceUtil.getPassword(getActivity()));

        HttpManager.postAsyn(Constant_Url.GET_INVITE_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络异常!!!");
            }

            @Override
            public void onResponse(String response) {
                //这里我们要对数据进行一个解析操作；
                dissDialog();
                if(!TextUtils.isEmpty(response)){
                    //解析

                    TuiGuangBean tuiGuangBean = new Gson().fromJson(response,TuiGuangBean.class);
                    if (tuiGuangBean != null) {
                        if(tuiGuangBean.getStatus().equals("0")){
                            //这里表示成功

                            List<String> url = tuiGuangBean.getUrl();
                            initTuiGuang(url);
                        }else{
                            //失败；
                            DisPlay(tuiGuangBean.getMessage());
                        }
                    }else{
                        DisPlay("网络异常");
                    }
                }else{
                    DisPlay("网络异常");
                }
            }
        },paramsMap);

    }

    /**
     * 这里要做的一个操作就是动态生成布局然后填充进去内容；
     * @param url
    */
    private void initTuiGuang(List<String> url) {

        if (url != null) {

            for (String s : url) {
                View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.layout_tui_guang, mLlTuiGuang, false);

                final TextView tvUrl = (TextView) inflate.findViewById(R.id.tv_url);
                tvUrl.setText(s);
                inflate.findViewById(R.id.tv_copy).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //这里是要复制操作；
                        BaseUtils.setClipString(getActivity(), tvUrl.getText().toString());
                        MyToast.showToast(getActivity(), "复制成功");
                    }
                });
                mLlTuiGuang.addView(inflate);

                //这里要做的一个操作就是添加二维码；

                addQrCode(s);
            }
        }
    }

    /**
     * 这里我们要做的一个逻辑就是生成二维码，并且添加的操作；
     * @param url
     */
    private void addQrCode(String url) {

        Bitmap bitmap = generateBitmap(url, BaseUtils.dip2px(getActivity(), 150), BaseUtils.dip2px(getActivity(), 150));

        ImageView imageView = new ImageView(getActivity());
        imageView.setImageBitmap(bitmap);

        mLlContainer.addView(imageView);
    }

    /**
     * 生成一个二维码的操作；
     * @param content
     * @param width
     * @param height
     * @return
     */
    public static Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public class TuiGuangBean{

        /**
         * message :
         * status : 0
         * url : ["http://m.cai310.net/user/reg.html?inviteid=353","http://m.yuecp.net/alone/reg.html?inviteid=353"]
         */

        private String message;
        private String status;
        private List<String> url;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public List<String> getUrl() {
            return url;
        }

        public void setUrl(List<String> url) {
            this.url = url;
        }
    }
}
